angular.module('maporders', [])
    .controller('mapordersCtrl', ['$scope', 'httpService', '$stateParams', '$filter', 'alertmsg', function($scope, httpService, $stateParams, $filter, alertmsg) {
        var id = $stateParams.id;
        var map, currentMarker, markers = [];


        function addMarker(orders) {
            angular.forEach(orders, function(v, k) {
                marker(v, k);
            });
        }

        $scope.isload = false;
        $scope.getOrders = function(page) {
            var url = "web/orders";
            if (id) {
                url += '/' + id;
            }
            httpService.query(url, { type: 'service', page: 1, limit: 30 }).then(function(res) {
                if (res.code == 200) {
                    $scope.orders = res.orders;
                    $scope.page = res.page;
                    addMarker(res.orders);
                }
            })
        };

        // 获取单个订单
        $scope.getOrderById = function() {
            httpService.query('web/orders/' + id).then(function(res) {
                if (res.code == 200) {
                    $scope.order = res.order;
                    marker(res.order);
                }
            });
        };


        function grabOrder() {
            var ext = currentMarker.getExtData();
            httpService.query('web/orders/' + ext.id + '/compete_order', undefined, 'post').then(function(res) {
                if (res.code == 200) {
                    $scope.orders.splice(ext.key, 1);

                    closeInfoWindow();
                    map.remove(markers);
                    addMarker($scope.orders);

                    alertmsg('抢单成功!你可以在<a style="color:#58c676!important;" href="#/mine/list/angular-flatpickr,orders">我的订单</a>中查看');
                } else {
                    alertmsg(res.msg);
                }
            });
        }

        $scope.$watch('isload', function(newdata, olddata) {
            if (!id) {
                $scope.getOrders(1);
            } else {
                $scope.getOrderById();
            }
        });

        // 加载
        var head = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = 'https://webapi.amap.com/maps?v=1.3&key=b1a49ba5623930057d0c66c629c98af9';
        head.appendChild(script);
        script.onreadystatechange = function() {
            if (this.readyState == 'complete') {

            }
        };

        script.onload = function() {
            $scope.isload = true;
            map = new AMap.Map('l-map', {
                resizeEnable: true,
                zoom: 5
            });
        };

        //关闭信息窗体
        function closeInfoWindow() {
            map.clearInfoWindow();
        }

        //构建信息窗体中显示的内容
        function createContent(order) {
            var content = [];
            content.push('<i class="icon-daishenhe"></i>' + $filter('date')(order.booking_date * 1000, 'yyyy-MM-dd HH:mm') + '');
            content.push('<i class="icon-dingdan"></i>预估面积: ' + order.square + '(㎡)|品牌:' + order.company_name) + '';
            return content.join("<br>");
        }

        // 构建信息窗体中显示的内容
        function openWindow(order) {
            var title = '本订单收入￥<span style="font-size: 20px;">' + order.total + '</span>';

            infoWindow = new AMap.InfoWindow({
                isCustom: true,
                content: createInfoWindow(title, createContent(order), order.id),
                // content: content.join("<br>"),
                offset: new AMap.Pixel(3, -50),
                closeWhenClickMap: true
            });
            infoWindow.open(map, [order.longitude, order.latitude]);
        }

        // 添加标签
        function marker(order, key) {
            var marker = new AMap.Marker({
                position: [order.longitude, order.latitude],
                extData: { id: order.id, key: key },
            });
            marker.setMap(map);
            markers.push(marker);

            marker.on('click', function(e) {
                currentMarker = marker;
                openWindow(order);
            });

        }

        //构建自定义信息窗体
        function createInfoWindow(title, content, id) {
            var info = document.createElement("div");
            info.className = "info yf-shadow";

            //可以通过下面的方式修改自定义窗体的宽高
            //info.style.width = "400px";
            // 定义顶部标题
            var top = document.createElement("div");
            var titleD = document.createElement("div");
            top.className = "info-top";
            titleD.innerHTML = title;
            top.appendChild(titleD);
            info.appendChild(top);

            // 定义中部内容
            var middle = document.createElement("div");
            middle.className = "info-middle";
            middle.style.backgroundColor = 'white';
            middle.innerHTML = content;
            info.appendChild(middle);

            var button = document.createElement("div");
            button.className = 'info-button';
            var btn = document.createElement("button");
            btn.className = "yf-btn";
            btn.innerHTML = "抢订单";
            btn.onclick = grabOrder;
            button.appendChild(btn);
            info.appendChild(button);


            // 定义底部内容
            var bottom = document.createElement("div");
            bottom.className = "info-bottom";
            bottom.style.position = 'relative';
            bottom.style.top = '-1px';
            bottom.style.margin = '0 auto';

            var sharp = document.createElement("img");
            sharp.src = "http://ogpxs89ck.bkt.clouddn.com/2D72C0CD752365C05E452C7AAE82526C.png";
            bottom.appendChild(sharp);
            info.appendChild(bottom);
            return info;
        }

    }]);
